package com.jeff.myvolley.Volley.toolbox;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Iterator;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONException;
import org.json.JSONObject;

import com.jeff.myvolley.Volley.AuthFailureError;
import com.jeff.myvolley.Volley.NetworkResponse;
import com.jeff.myvolley.Volley.ParseError;
import com.jeff.myvolley.Volley.Request;
import com.jeff.myvolley.Volley.Response;
import com.jeff.myvolley.Volley.VolleyLog;

public class MultipartFileRequest extends Request<JSONObject> {

//    @Override
//	public Map<String, String> getHeaders() throws AuthFailureError {
//		Map<String,String> heads = new HashMap<String, String>();
//    	heads.put("Content-Type", "multipart/form-data");
//    	return heads;
//	}

	private MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));

    private static final String FILE_PART_NAME = "logo_file";
    private static final String STRING_PART_NAME = "text";

    private final Response.Listener<JSONObject> mListener;
    private final File mFilePart;
    private final JSONObject mStringPart;

    private String head;
    public MultipartFileRequest(String url, Response.ErrorListener errorListener, Response.Listener<JSONObject> listener, JSONObject json)
    {
    	this(url, errorListener, listener, null, null, json);
    }
    public MultipartFileRequest(String url, Response.ErrorListener errorListener, Response.Listener<JSONObject> listener, File file , String fileName, JSONObject json)
    {
        super(Method.POST, url, errorListener);

        mListener = listener;
        mFilePart = file;
        mStringPart = json;
        buildMultipartEntity(fileName);
    }

    private void buildMultipartEntity(String fileName)
    {
    	if (mFilePart != null) {
   		 entity.addPart(fileName, new FileBody(mFilePart));
		}
        try
        {
        	Iterator<String> iterator = mStringPart.keys();
        	while (iterator.hasNext()) 
        	{
				String next = iterator.next();
				try {
					entity.addPart(next, new StringBody(mStringPart.getString(next),Charset.forName("UTF-8")));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
            
        }
        catch (UnsupportedEncodingException e)
        {
            VolleyLog.e("UnsupportedEncodingException");
        }
    }

    @Override
    public String getBodyContentType()
    {
        return entity.getContentType().getValue();
    }

    @Override
    public byte[] getBody() throws AuthFailureError
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try
        {
            entity.writeTo(bos);
        }
        catch (IOException e)
        {
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response)
    {
    	try {
            String jsonString =
                new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response)
    {
        mListener.onResponse(response);
    }
    
//    public  void setHeads(String string)
//    {
//    	head = string;
//    }
}